package cn.itcast.bos.web.action;

import java.io.File;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.take_delivery.Promotion;
import cn.itcast.bos.service.PromotionService;
import cn.itcast.bos.web.action.common.BaseAction;

@ParentPackage(value="json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class PromotionAction extends BaseAction<Promotion> {

	@Autowired
	private PromotionService promotionService;
	
	//属性驱动
	private File titleImgFile;//表单中上传的文件
	private String titleImgFileFileName;//上传文件的文件名
	
	public void setTitleImgFile(File titleImgFile) {
		this.titleImgFile = titleImgFile;
	}

	public void setTitleImgFileFileName(String titleImgFileFileName) {
		this.titleImgFileFileName = titleImgFileFileName;
	}


	@Action(value="promotion_save",results={@Result(name="success",type="redirect",location="./pages/take_delivery/promotion.html")})
	public String save() throws Exception {
		//获取绝对路劲，用于上传
		String savePath = ServletActionContext.getServletContext().getRealPath("/upload/");
		//获取相对路径，用于保存数据到数据库
		String saveUrl = ServletActionContext.getRequest().getContextPath()+"/upload/";
		//生成随机名
		String uuid = UUID.randomUUID().toString().replace("-", "");
		String extension = titleImgFileFileName.substring(titleImgFileFileName.lastIndexOf("."));
		String randomFileName = uuid+extension;
		File destFile = new File(savePath+"/"+randomFileName);
		FileUtils.copyFile(titleImgFile, destFile);
		
		//将相对路径保存到model对象中
		model.setTitleImg(saveUrl+randomFileName);
		
		//调用业务层
		promotionService.save(model);
		return SUCCESS;
	}
	
	@Action(value="promotion_pageQuery",results={@Result(name="success",type="json")})
	public String pageQuery()  {
		Pageable pageable = new PageRequest(page-1, rows);
		//调用业务层查询
		Page<Promotion> pageData = promotionService.pageQuery(pageable);
		pushPageDataToValueStack(pageData);
		return SUCCESS;
	}
}
